package cn.core.tool.util;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * 响应数据
 */
@Data
@Accessors(chain = true)
public class Res<T> implements Serializable {

  private static final long serialVersionUID = 1L;

  /**
   * 请求成功
   */
  private boolean succ;

  /**
   * 消息
   */
  private String msg;

  /**
   * 第几页
   */
  private Long page;

  /**
   * 多少条
   */
  private Long rows;

  /**
   * 数据量
   */
  private Long count;

  /**
   * 数据
   */
  private Collection<T> data;

  public Res() {
    super();
    this.succ = true;
    this.msg = "";
    this.page = 1l;
    this.rows = 10l;
    this.count = 0l;
    this.data = Collections.emptyList();
  }

  public Res(String succMsg) {
    super();
    this.succ = true;
    this.msg = succMsg;
    this.page = 1l;
    this.rows = 10l;
    this.count = 0l;
    this.data = Collections.emptyList();
  }

  public Res<T> setData(Collection<T> data) {
    if (data != null) {
      this.count = (long) data.size();
      this.data = data;
    }
    return this;
  }

  public Res<T> setData(T data) {
    if (data != null) {
      this.count = 1l;
      this.data = new ArrayList<T>();
      this.data.add(data);
    }
    return this;
  }

  public Res<T> setData(Paging<T> paging) {
    this.page = paging.getPage();
    this.rows = paging.getRows();
    this.count = paging.getCount();
    if (paging.getData() != null) {
      this.data = paging.getData();
    } else {
      this.data = Collections.emptyList();
    }
    return this;
  }

  public Res<T> setException(String errMsg) {
    succ = false;
    this.msg = errMsg;
    return this;
  }

}
